package com.fanrui.code.message;

import java.util.HashSet;
import java.util.Set;

import com.fanrui.code.util.CommandsUtil;
import com.fanrui.code.util.logger.Stdout;
import com.fanrui.proto.cmd.CmdWrapper;
import com.fanrui.proto.cmd.CmdWrapper.CmdType;
import com.fanrui.proto.cmd.ServerCmdWrapper;
import com.google.protobuf.MessageLite;

import io.netty.channel.Channel;

public class PlayerSession {

	private long playerId;
	
	private Channel channel;

	private static Set<CmdType> filterLog = new HashSet<>();
	
	public PlayerSession(long playerId, Channel channel) {
		super();
		this.playerId = playerId;
		this.channel = channel;
	}
	
	/**
	 * 判断这个Sender的channel是不是同一个
	 * 
	 * @param channel
	 * @return
	 */
	public boolean isSameSocket(Channel channel) {
		return this.channel.compareTo(channel) == 0;
	}

	/**
	 * session 建立完成后调用
	 */
	public void afterCreate() {
		Stdout.GET().info(String.format("session 建立完成,id:%d", playerId));
	}
	
	/**
	 * session 销毁后调用
	 */
	public void beforeRemove() {
		Stdout.GET().info(String.format("session 销毁,id:%d", playerId));
	}

	public void changeChannel(Channel channel) {
		if(null != this.channel && this.channel.isOpen()){
			this.channel.close();
		}
		this.channel = channel;
	}

	public long getPlayerId() {
		return playerId;
	}
	
	public void send(CmdWrapper cmdWrapper) {
		ServerCmdWrapper serverCmdWrapper = ServerCmdWrapper.newBuilder().setCmdWrapper(cmdWrapper)
				.setPlayerId(this.playerId).build();
		this.channel.writeAndFlush(serverCmdWrapper);
		CmdType cmdType = serverCmdWrapper.getCmdWrapper().getCmdType();
		if (!filterLog.contains(cmdType)) {
//			Stdout.GET().info("Hall->GATE {}",CommandsUtil.toString(serverCmdWrapper));
		}
	}

	public void send(MessageLite message) {
		CmdWrapper cmdWapper = CommandsUtil.wrapper(-1, message);
		this.send(cmdWapper);
	}

	public Channel getChannel() {
		return channel;
	}

	public void setChannel(Channel channel) {
		this.channel = channel;
	}
}
